package org.ilc.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;
import org.ilc.Bootstrap;
import org.ilc.FileLogger;
import org.ilc.push.IHeader;
import org.ilc.push.ISendTask;
import org.ilc.push.Message;
import org.ilc.socketserver.Response;

public class SendTask implements ISendTask {

	private static Log log = LogFactory.getLog("SendTask");
	
	public void send(Message message){
		try{
			if(log.isDebugEnabled()){
				log.debug("invoke send task...");
			}
			String authUser=message.getAccount();
			IoSession session=	Bootstrap.getContext().getAcceptor().getSession(authUser);
			if(null==session){
//			if(null==session || session.isClosing()){
				if(log.isInfoEnabled()){
					//log.info("message send failure,"+authUser+" not connected");
				}
				message.setStatus(Message.STATUS_SEND_FAILUER);
				
			}else{
			
				String content=message.getContent();
				if(null==content){
					if(log.isInfoEnabled()){
						log.info("message send failure,message content is null");
					}
					message.setStatus(Message.STATUS_SEND_FAILUER);
				}else{
					Response response=new Response(session);
					response.setBody(message.getContent().getBytes(IHeader.HEADER_ENCODING_CHARSET));
					response.flush();
					response.destroy();

                    //更新状态 为成功
					message.setStatus(Message.STATUS_SEND_SUCESSFUL);
					if(log.isInfoEnabled()){
						log.info("message send sucessful, user:"+authUser);
					}

                    if(Bootstrap.getContext().getAppConfig().getBoolean(org.ilc.Constants.SERVER_DEBUG)) {
                        new FileLogger().log(SendTask.class, "Server send message: " + content + " to " + authUser);
                    }
				}
				
			}
			if(null!= Bootstrap.getContext().getSendListener())
				Bootstrap.getContext().getSendListener().messageSened(message);
		}catch(Exception e){
			//异常
			message.setStatus(Message.STATUS_SEND_FAILUER);
			if(null!= Bootstrap.getContext().getSendListener())
				Bootstrap.getContext().getSendListener().onException(message, e);
		}
	
	}

}
